package com.mengxuegu.springboot.config;

import com.mengxuegu.springboot.filter.MyFilter;
import com.mengxuegu.springboot.listener.MyListener;
import com.mengxuegu.springboot.servlet.HelloServlet;
import com.mengxuegu.springboot.servlet.HelloServlet2;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.Arrays;

@Configuration
public class MyServletConfig {
    @Bean
    public WebServerFactoryCustomizer webServerFactoryCustomizer() {
        return new WebServerFactoryCustomizer() {
            @Override
            public void customize(WebServerFactory factory) {
                ConfigurableWebServerFactory factory1 = (ConfigurableWebServerFactory) factory;
                ((ConfigurableWebServerFactory) factory).setPort(8082);
            }
        };
    }

    /**
     * 注册servlet组件
     */
    @Bean
    public ServletRegistrationBean helloServlet() {
        ServletRegistrationBean<HelloServlet> bean = new ServletRegistrationBean<>(new HelloServlet(), "/hello/*");
        // 设置servlet组件参数
        bean.setLoadOnStartup(3);
        return bean;
    }

    /**
     * 注册servlet组件
     */
    @Bean
    public ServletRegistrationBean helloServlet2() {
        ServletRegistrationBean<HelloServlet2> bean = new ServletRegistrationBean<>(new HelloServlet2(), "/hello/2");
        // 设置servlet组件参数
        bean.setLoadOnStartup(2);
        return bean;
    }

    /**
     * 注册Filter组件
     */
    @Bean
    public FilterRegistrationBean myFilter() {
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new MyFilter());
        bean.setUrlPatterns(Arrays.asList("/hello"));
        return bean;
    }

    @Bean
    public ServletListenerRegistrationBean myListener() {
        ServletListenerRegistrationBean<MyListener> bean = new ServletListenerRegistrationBean<>(new MyListener());
        return bean;
    }

}
